package com.sophossystems.client.asmon.dao.spring;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.transform.Transformers;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.transaction.annotation.Transactional;

import com.sophossystems.client.asmon.dao.PrivilegeDao;
import com.sophossystems.client.asmon.dto.PrivilegeDTO;
import com.sophossystems.client.asmon.dto.PrivilegePkDTO;
import com.sophossystems.client.asmon.exceptions.DaoException;
import com.sophossystems.client.asmon.hibernate.Privilege;

public class PrivilegeDaoImpl extends AbstractDAO implements  PrivilegeDao
{
	
	private static Logger log = Logger.getLogger(PrivilegeDaoImpl.class);
	/**
	 * Method 'insert'
	 * 
	 * @param dto
	 * @return ActivityPk
	 */
	@Override
	@Transactional
	public PrivilegePkDTO insert(final PrivilegeDTO dto){
		PrivilegePkDTO exito =null ;
	try {
		 exito = (PrivilegePkDTO) getHibernateTemplate().execute(new HibernateCallback() {
			/**
			 * {@inheritDoc}
			 * 
			 * @see org.springframework.orm.hibernate3.HibernateCallback#doInHibernate(org.hibernate.Session)
			 */
			@Override
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
			    Transaction tx = session.beginTransaction();
			    PrivilegePkDTO pk = null;
			    Privilege privilege = new Privilege();
			    privilege.mapper(dto);
			    session.save(privilege);
			    tx.commit();
			    
			    try{
			    	//revisar busquedas
			    	PrivilegePkDTO res = findLastInsert();
			    	pk = new PrivilegePkDTO();
			    	pk.setIdPrivilege(res.getIdPrivilege());
			    }catch (DaoException es) {
					
			    	throw new HibernateException("Insersion: " +es.getMessage());
				}
				return pk;
			
				
			}

			
		});
	
	} catch (final Exception e) {
		logger.error("Error: getActivity, cause: " + e.getMessage(), e);
		
	}
	return exito;
}

		
	/** 
	 * Updates a single row in the Activity table.
	 */
	@Override
	@Transactional
	public void update(final PrivilegeDTO dto) throws DaoException
	{
		try {
			 getHibernateTemplate().execute(new HibernateCallback() {
				/**
				 * {@inheritDoc}
				 * 
				 * @see org.springframework.orm.hibernate3.HibernateCallback#doInHibernate(org.hibernate.Session)
				 */
				@Override
				public Object doInHibernate(Session session)
						throws HibernateException, SQLException {
					PrivilegePkDTO pk = null;
					PrivilegeDTO res = null;
					Transaction tx = session.beginTransaction();
					// Aqui primero se busca si existe el registro
					try {
						res = findByPrimaryKey(dto
								.getIdActivity());
						pk = new PrivilegePkDTO();
						pk.setIdPrivilege(res.getIdActivity());
					} catch (DaoException es) {
						throw new HibernateException(
								"Update ActivityDao: "
										+ es.getMessage());
					}
					///aqui se actualizar los campos y con los de la entrada  
					//cuidado de actualiza todo.
					Privilege persis = new Privilege();
					persis.mapper(dto);
					persis.setIdPrivilege(res.getIdPrivilege());
					session.update(persis);
					tx.commit();
					return null;
				}		
			});
		} catch (final Exception e) {
			logger.error("Error: getActivity, cause: " + e.getMessage(), e);
			throw new DaoException("Error: getActivity, cause: " + e.getMessage());
		}
	
		
	
	}

	/** 
	 * Deletes a single row in the Activity table.
	 */
	@Override
	@Transactional
	public void delete(final PrivilegePkDTO pk) throws DaoException
	{
		
		
		try {
			 getHibernateTemplate().execute(new HibernateCallback() {
				/**
				 * {@inheritDoc}
				 * 
				 * @see org.springframework.orm.hibernate3.HibernateCallback#doInHibernate(org.hibernate.Session)
				 */
				@Override
				public Object doInHibernate(Session session)
						throws HibernateException, SQLException {
				    Transaction tx = session.beginTransaction();
				    Privilege privilege = (Privilege)session.load(Privilege.class,pk.getIdPrivilege() );
				    session.delete(privilege);
					tx.commit();
					return null;
				}		
			});
		} catch (final Exception e) {
			logger.error("Error: getActivity, cause: " + e.getMessage(), e);
			throw new DaoException("Error: getActivity, cause: " + e.getMessage());
		}
	}
	
	/**
	 * Method 'getTableName'
	 * 
	 * @return String
	 */
	public String getTableName()
	{
		return "Privilege";
	}

	/** 
	 * Returns all rows from the Privilege table that match the criteria 'idPrivilege = :idPrivilege'.
	 */
	@Override
	@Transactional
	public PrivilegeDTO findByPrimaryKey(final int idPrivilege)
			throws DaoException	{
		PrivilegeDTO privilege = null;
		try {
			privilege = (PrivilegeDTO)getHibernateTemplate().execute(
					new HibernateCallback() {
						
						@SuppressWarnings("unchecked")
						@Override
						public Object doInHibernate(Session session) throws HibernateException,
								SQLException {
						
							PrivilegeDTO privilege = null;
							Query oQuery = session.createQuery("SELECT p.idPrivilege as idPrivilege, p.idRole as idRole, p.idActivity as idActivity," +
									" p.enabled as enable FROM " + getTableName() + " p WHERE p.idPrivilege = :id_privilege");
							oQuery.setInteger(0, idPrivilege);
							List<PrivilegeDTO> lista = oQuery.setResultTransformer(
									Transformers.aliasToBean(Privilege.class)).list();
							if(lista != null && lista.size() > 0){
								privilege = lista.get(0);
								return privilege;
							}else{
								
							}
							return privilege;
						}
					});
//			List<PrivilegeDTO> list = jdbcTemplate.query("SELECT idPrivilege, idRole, idActivity, enabled FROM " + getTableName() + " WHERE idPrivilege = ?", this,idPrivilege);
//			return list.size() == 0 ? null : list.get(0);
		}
		catch (Exception e) {
			logger.error("Error: Privilege, cause: " + e.getMessage(), e);
			throw new DaoException("Query failed", e);
		}
		return privilege;
	}

	/** 
	 * Returns all rows from the Privilege table that match the criteria ''.
	 */
	@Override
	@SuppressWarnings("unchecked")
	@Transactional
	public List<PrivilegeDTO> findAll() throws DaoException	{
		List<PrivilegeDTO> privilege = null;
		try {
			privilege = (List<PrivilegeDTO>)getHibernateTemplate().execute(
					new HibernateCallback() {
						
						@Override
						public Object doInHibernate(Session session) throws HibernateException,
								SQLException {
						
							Query oQuery = session.createQuery("SELECT p.idPrivilege as idPrivilege, p.idRole as idRole, p.idActivity as idActivity," +
									" p.enabled as enabled FROM " + getTableName() + " p ORDER BY p.idPrivilege");
							List<PrivilegeDTO> lista = oQuery
									.setResultTransformer(Transformers
											.aliasToBean(PrivilegeDTO.class)).list();
							return lista;
						}
					});
//			return jdbcTemplate.query("SELECT idPrivilege, idRole, idActivity, enabled FROM " + getTableName() + " ORDER BY idPrivilege", this);
		}
		catch (Exception e) {
			logger.error("Error: Privilege, cause: " + e.getMessage(), e);
			throw new DaoException("Query failed", e);
		}
		return privilege;
	}

	/** 
	 * Returns all rows from the Privilege table that match the criteria 'idPrivilege = :idPrivilege'.
	 */
	@Override
	@Transactional
	public List<PrivilegeDTO> findWhereIdPrivilegeEquals(final int idPrivilege)
			throws DaoException	{
		List<PrivilegeDTO> list = new ArrayList<PrivilegeDTO>();
		PrivilegeDTO privilege =  this.findByPrimaryKey(idPrivilege);
		list.add(privilege);
		return list;
		
	}

	/** 
	 * Returns all rows from the Privilege table that match the criteria 'idRole = :idRole'.
	 
	@Transactional
	public List<PrivilegeDTO> findWhereIdRoleEquals(int idRole) throws DaoException
	{
		try {
			return jdbcTemplate.query("SELECT idPrivilege, idRole, idActivity, enabled FROM " + getTableName() + " WHERE idRole = ? ORDER BY idRole", this,idRole);
		}
		catch (Exception e) {
			throw new DaoException("Query failed", e);
		}
		
	}*/

	/** 
	 * Returns all rows from the Privilege table that match the criteria 'idActivity = :idActivity'.
	 
	@Transactional
	public List<PrivilegeDTO> findWhereIdActivityEquals(int idActivity) throws DaoException
	{
		try {
			return jdbcTemplate.query("SELECT idPrivilege, idRole, idActivity, enabled FROM " + getTableName() + " WHERE idActivity = ? ORDER BY idActivity", this,idActivity);
		}
		catch (Exception e) {
			logger.error("Error: Privilege, cause: " + e.getMessage(), e);
			throw new DaoException("Query failed", e);
		}
		
	}*/

	/** 
	 * Returns all rows from the Privilege table that match the criteria 'enabled = :enabled'.
	 
	@Transactional
	public List<PrivilegeDTO> findWhereEnabledEquals(int enabled) throws DaoException
	{
		try {
			return jdbcTemplate.query("SELECT idPrivilege, idRole, idActivity, enabled FROM " + getTableName() + " WHERE enabled = ? ORDER BY enabled", this,enabled);
		}
		catch (Exception e) {
			logger.error("Error: Privilege, cause: " + e.getMessage(), e);
			throw new DaoException("Query failed", e);
		}
		
	}*/

	/** 
	 * Returns the rows from the Privilege table that matches the specified primary-key value.
	 
	public PrivilegeDTO findByPrimaryKey(PrivilegePkDTO pk) throws DaoException
	{
		return findByPrimaryKey( pk.getIdPrivilege() );
	}*/

	@Override
	public PrivilegePkDTO findLastInsert() throws DaoException {
		PrivilegePkDTO privilege = null;
		try {
			privilege = (PrivilegePkDTO) getHibernateTemplate().execute(
					new HibernateCallback() {

						@Override
						public Object doInHibernate(Session session)
								throws HibernateException, SQLException {
							
							Query oQuery = session
									.createQuery("SELECT max(p.idPrivilege) as idPrivilege FROM "
											+ getTableName()
											+ " p ");
							
							PrivilegePkDTO privilegeDto = (PrivilegePkDTO) oQuery
									.setResultTransformer(Transformers
											.aliasToBean(PrivilegePkDTO.class)).list().get(0);
							return privilegeDto;
						}
					});
		
		} catch (Exception e) {
			logger.error("Error: PrivilegeDaoImp, cause: " + e.getMessage(), e);
			throw new DaoException("Query failed", e);
		}
		return privilege;

	}
	
}
